package com.simtop.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.Key;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.Operate;
import com.simtop.pojo.User;
import com.simtop.pojo.experiment.ExperimentScore;
import com.simtop.pojo.experiment.ExperimentScoreExport;
import com.simtop.pojo.ilabresult.IlabSport;
import com.simtop.pojo.ilabresult.Step;
import com.simtop.service.ExperimentScoreService;
import com.simtop.service.OperateService;
import com.simtop.util.ExcelUtils;
import com.simtop.util.IlabUtil;
import com.simtop.util.JwtUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author lvyongwei
 */
@Controller
@RequestMapping("/u3d")
@CrossOrigin
public class U3dSportController {

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private ExperimentScoreService experimentScoreService;

    @Autowired
    private OperateService operateService;

    @Autowired
    private ExcelUtils excelUtils;

    private Logger logger = LoggerFactory.getLogger(U3dSportController.class);

    @PostMapping("/getUserName")
    @ResponseBody
    public ServerResponse<String> insertSport(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        String userName = u.getUsername();
        return ServerResponse.createBySuccess(userName);
    }


    /**
     * 上传实验报告到ilab并且添加到本地数据库
     * @return
     */
    @PostMapping("/score")
    @ResponseBody
    public ServerResponse<String> insertSport(@RequestBody ExperimentScore experimentScore, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        /**
         * 设置用户id
         */
        experimentScore.setUserId(Long.valueOf(u.getId()));
        //从ilab平台登录账户,即需要成绩上传到ilab平台
        if (u.getRoleId().equals(5)) {
            /**
             * 设置传给ilab的值
             */
            IlabSport ilabSport = experimentScore.getIlabSport();
            ilabSport.setOriginId(UUID.randomUUID().toString().replaceAll("-","_"));
            ilabSport.setAppid((int)Key.issuerId);
            ilabSport.setTitle("转杯色纺纱工艺设计与打样虚拟仿真实验");
            ilabSport.setUsername(u.getLoginName());
            ilabSport.getSteps().forEach(
                    step -> {
                        step.setEvaluation("百分制");
                        if(step.getTitle().equals("实验简介") || step.getTitle().equals("安全教育")){
                            step.setScoringModel("时长+测试");
                        }else{
                            step.setScoringModel("操作+测试");
                        }
                    }
            );
            //提交成绩
            String response = ilabUtil.submitGrade(ilabSport, u.getAccessToken());
            System.out.println(response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if(jsonObject.getInteger("code") != 0){
                Operate operate = new Operate("ilab用户提交实验成绩",u.getUsername(),u.getRoleId(),"提交失败",new Date(), JSONObject.toJSONString(experimentScore));
                operateService.insertOperate(operate);
                return ServerResponse.createByErrorMsg("上传ilab实验成绩失败");
            }
        }
        try {
            Operate operate = new Operate("提交实验成绩",u.getUsername(),u.getRoleId(),"提交成功",new Date(), JSONObject.toJSONString(experimentScore));
            operateService.insertOperate(operate);
            experimentScoreService.insertExperimentScore(experimentScore);
            return ServerResponse.createBySuccessMsg("上传成绩成功");
        } catch (Exception e) {
            e.printStackTrace();
            Operate operate = new Operate("提交实验成绩",u.getUsername(),u.getRoleId(),"提交失败",new Date(), JSONObject.toJSONString(experimentScore));
            operateService.insertOperate(operate);
            return ServerResponse.createByErrorMsg("上传成绩失败");
        }
    }

    /**
     * 上传实验报告到ilab并且添加到本地数据库
     * @return
     */
    @PostMapping("/uploadLabReport")
    @ResponseBody
    public ServerResponse<String> uploadLabReport(@RequestBody IlabSport ilabSport, HttpServletRequest request) {
        ExperimentScore experimentScore = new ExperimentScore();
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        /**
         * 设置用户id
         */
        experimentScore.setUserId(Long.valueOf(u.getId()));
        //从ilab平台登录账户,即需要成绩上传到ilab平台
        if (u.getRoleId().equals(5)) {
            /**
             * 设置传给ilab的值
             */
            experimentScore.setIlabSport(ilabSport);
            IlabSport ilabSport2 = experimentScore.getIlabSport();
            ilabSport2.setOriginId(UUID.randomUUID().toString().replaceAll("-","_"));
            ilabSport2.setAppid((int)Key.issuerId);
            ilabSport2.setTitle("转杯色纺纱工艺设计与打样虚拟仿真实验");
            ilabSport2.setUsername(u.getLoginName());
            ilabSport2.getSteps().forEach(
                    step -> {
                        step.setEvaluation("百分制");
                        if(step.getTitle().equals("实验简介") || step.getTitle().equals("安全教育")){
                            step.setScoringModel("时长+测试");
                        }else{
                            step.setScoringModel("操作+测试");
                        }
                    }
            );
            //提交成绩
            String response = ilabUtil.submitGrade(ilabSport2, u.getAccessToken());
            System.out.println(response);
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println(jsonObject);
            if(jsonObject.getInteger("code") != 0){
                Operate operate = new Operate("ilab用户提交实验成绩",u.getUsername(),u.getRoleId(),"提交失败",new Date(), JSONObject.toJSONString(experimentScore));
                operateService.insertOperate(operate);
                return ServerResponse.createByErrorMsg("上传ilab实验成绩失败");
            }
        }
        try {
            Operate operate = new Operate("提交实验成绩",u.getUsername(),u.getRoleId(),"提交成功",new Date(), JSONObject.toJSONString(experimentScore));
            operateService.insertOperate(operate);
            experimentScoreService.insertExperimentScore(experimentScore);
            return ServerResponse.createBySuccessMsg("上传成绩成功");
        } catch (Exception e) {
            e.printStackTrace();
            Operate operate = new Operate("提交实验成绩",u.getUsername(),u.getRoleId(),"提交失败",new Date(), JSONObject.toJSONString(experimentScore));
            operateService.insertOperate(operate);
            return ServerResponse.createByErrorMsg("上传成绩失败");
        }
    }


    /**
     * 获取所有实验成绩
     * @param request
     * @param data
     * @return
     */
    @PostMapping("/getAllScore")
    @ResponseBody
    public ServerResponse<Object> getAllScore(HttpServletRequest request,@RequestBody String data) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        System.out.println(jsonObject);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        /**
         * 搜索条件
         */
        String school = jsonObject.getString("school");
        Date beginDate = jsonObject.getDate("beginDate");
        Date endDate = jsonObject.getDate("endDate");
        /**
         * 设置搜索条件
         */
        ExperimentScore experimentScore = new ExperimentScore();
        experimentScore.setSchool(school);
        experimentScore.setBeginDate(beginDate);
        experimentScore.setEndDate(endDate);
        experimentScore.setRoleId(u.getRoleId());
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum = 1;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize = 10;
        }
        try {
            List<ExperimentScore> experimentScores = null;
            PageInfo<ExperimentScore> pageInfo = null;
            if(u.getRoleId() == 1 || u.getRoleId() == 2){
                PageHelper.startPage(pageNum,pageSize);
                experimentScores = experimentScoreService.getAllExperimentScore(experimentScore);
                pageInfo = new PageInfo<>(experimentScores);
            } else{
                experimentScore.setUserId((long) u.getId());
                PageHelper.startPage(pageNum,pageSize);
                experimentScores = experimentScoreService.getAllExperimentScore(experimentScore);
                pageInfo = new PageInfo<>(experimentScores);
            }
            return ServerResponse.createBySuccess("查询成功",pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取成绩失败");
        }
    }

    /**
     * 导出所有实验成绩
     * @param request
     * @param response
     * @param beginDate
     * @param endDate
     * @param school
     * @return
     */
    @GetMapping("/exportScore")
    @ResponseBody
    public void exportScore(HttpServletRequest request, HttpServletResponse response,String beginDate,String endDate,String school) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ExperimentScoreExport> experimentScoreExports = experimentScoreService.experimentExport(beginDate, endDate, school);
        experimentScoreExports.forEach(
                score -> {
                    long date = Long.valueOf(score.getUseTime());
                    int  hours = (int)((date % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    int minutes = (int)((date % (1000 * 60 * 60)) / (1000 * 60));
                    int seconds = (int)((date % (1000 * 60)) / 1000);
                    String s = (hours < 10 ? ("0" + hours) : hours) + ":"
                     + ((minutes < 10 ? ("0" + minutes) : minutes)) + ":"
                     + (seconds < 10 ? ("0" + seconds) : seconds);
                    score.setUseTime(s);
                }
        );
        excelUtils.cooperationData(request,response,experimentScoreExports,"实验成绩",ExperimentScoreExport.class);
    }
}
